package com.xuecheng.content.service.jobhandler;

import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.feignclient.SearchServiceClient;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.model.dto.CourseIndex;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MessageProcessAbstract;
import com.xuecheng.messagesdk.service.MqMessageService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * @author: Hes
 * @description 课程发布任务调度
 * @date: 2023/6/24 11:39
 */
@Component
@Slf4j
public class CoursePublishTask extends MessageProcessAbstract {

    @Autowired
    CoursePublishService coursePublishService;

    @Autowired
    SearchServiceClient searchServiceClient;

    @Autowired
    CoursePublishMapper coursePublishMapper;

    @Autowired
    RedisTemplate redisTemplate;


    //任务调度入口
    @XxlJob("coursePublishJobHandler")
    public void coursePublishJobHandler() throws Exception {
        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        log.debug("shardIndex=" + shardIndex + ",shardTotal=" + shardTotal);
        //参数:分片序号、分片总数、消息类型、一次最多取到的任务数量、一次任务调度执行的超时时间
        process(shardIndex, shardTotal, "course_publish", 30, 60);
    }

    @Override
    public boolean execute(MqMessage mqMessage) {
        long courseId = Integer.parseInt(mqMessage.getBusinessKey1());
        //页面静态化
        generateCourseHtml(mqMessage, courseId);
        //存储搜索引擎
        saveCourseIndex(mqMessage, courseId);
        //存储缓存
        saveCourseCache(mqMessage, courseId);
        return false;
    }

    /**
     * 存储缓存redis
     *
     * @param mqMessage
     * @param courseId
     */
    private void saveCourseCache(MqMessage mqMessage, Long courseId) {
        Long id = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
        int stageThree = mqMessageService.getStageThree(id);
        if (stageThree > 0) {
            log.debug("课程信息已保存过了,课程id:{}", courseId);
            return;
        }
        Object o = redisTemplate.opsForValue().get("course" + courseId);
        if (o!=null){
            log.debug("课程信息已缓存至redis,课程id:{}", courseId);
            return;
        }
        CoursePublish coursepublish = coursePublishService.getCoursepublish(courseId);
        redisTemplate.opsForValue().set("course:" + courseId, coursepublish.toString(), 1, TimeUnit.DAYS);

    }

    /**
     * 存储搜索引擎
     *
     * @param mqMessage
     * @param courseId
     */
    private void saveCourseIndex(MqMessage mqMessage, Long courseId) {
        MqMessageService mqMessageService = this.getMqMessageService();
        Long id = mqMessage.getId();
        int stageTwo = mqMessageService.getStageTwo(id);
        if (stageTwo > 0) {
            log.debug("保存课程索引信息已完成，直接返回,课程id:{}", courseId);
        }
        boolean b = saveCourseIndex(courseId);
        if (b) {
            mqMessageService.completedStageTwo(id);
        }
    }

    public boolean saveCourseIndex(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        CourseIndex courseIndex = new CourseIndex();
        BeanUtils.copyProperties(coursePublish, courseIndex);
        Boolean result = searchServiceClient.add(courseIndex);
        if (!result) {
            XueChengPlusException.cast("添加课程索引失败");
        }
        return true;
    }

    /**
     * 页面静态化
     *
     * @param mqMessage
     * @param courseId
     */
    private void generateCourseHtml(MqMessage mqMessage, Long courseId) {
        Long id = mqMessage.getId();
        MqMessageService mqMessageService = this.getMqMessageService();
        int stageOne = mqMessageService.getStageOne(id);
        if (stageOne > 0) {
            log.debug("课程静态化已完成，直接返回,课程id：{}", courseId);
            return;
        }
        try {
            TimeUnit.SECONDS.sleep(10);

        } catch (InterruptedException e) {
            XueChengPlusException.cast("课程静态失败");
        }
        File file = coursePublishService.generateCourseHtml(courseId);
        if (file != null) {
            coursePublishService.uploadCourseHtml(courseId, file);
        }
        //保存第一阶段状态
        mqMessageService.completedStageOne(id);
    }


}
